package com.gitlab.lucky.weixin.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.gitlab.lucky.common.dao.mapper.WeixinGzhUserMapper;
import com.gitlab.lucky.common.dao.model.WeixinGzhIntegrationRecord;
import com.gitlab.lucky.common.dao.model.WeixinGzhUser;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.service.ServiceImpl;
import com.gitlab.lucky.common.utils.DateUtil;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-05 11:27
 **/
@Service
public class WeixinGzhUserService extends ServiceImpl<WeixinGzhUserMapper, WeixinGzhUser> {
    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinGzhUserService.class);
    @Autowired
    private WeixinUtil weixinUtil;
    @Autowired
    private WeixinGzhUserMapper weixinGzhUserMapper;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;

    /**
     * 从微信获取用户信息
     *
     * @param openId
     * @return
     */
    public WeixinGzhUser insertUserInfo(String openId, Integer platform,JSONObject json){
        //获取accessToken
        String accessToken = weixinUtil.getAccessToken(platform);
        //调用微信获取微信用户信息
        String url = String.format(Constant.GET_WX_USER_INFO_URL, accessToken, openId);
        //请求
        String result = HttpUtil.get(url);
        //结果集转对象
        WeixinGzhUser weixinGzhUser = JSONObject.parseObject(result, WeixinGzhUser.class);
        //设置平台
        weixinGzhUser.setPlatform(platform);
        //设置邀请人
        if (StringUtils.isBlank(weixinGzhUser.getQrSceneStr())) {
            weixinGzhUser.setQrSceneStr(null);
        }
        weixinGzhUser.setIntegration(json.getInteger(Constant.INIT_USER_COUNT));
        try {
            this.insertSelective(weixinGzhUser);
        }catch (Exception e){
            LOGGER.info("用户端已存在:{}",JSONObject.toJSONString(weixinGzhUser));
        }

        WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
        weixinGzhIntegrationRecord.setCreateTime(new Date());
        weixinGzhIntegrationRecord.setPlatform(platform);
        weixinGzhIntegrationRecord.setType(CodeEnum.INIT_USER.getCode());
        weixinGzhIntegrationRecord.setOpenId(openId);
        weixinGzhIntegrationRecord.setIntegration("+"+json.getInteger(Constant.INIT_USER_COUNT));
        weixinGzhIntegrationRecord.setIntegrationBalance(weixinGzhUser.getIntegration());
        weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);
        return weixinGzhUser;
    }

    /**
     * 更新用户信息，绑定手机号。
     *
     * @param openId
     * @param phone
     * @param platform
     * @return
     */
    public WeixinGzhUser updateUserInfo(String openId, String phone, Integer platform) {
        WeixinGzhUser wxUserInfoByOpenId = getWxUserInfoByOpenId(openId, platform);
        //获取accessToken
        String accessToken = weixinUtil.getAccessToken(platform);
        //调用微信获取微信用户信息
        String url = String.format(Constant.GET_WX_USER_INFO_URL, accessToken, openId);
        //请求
        String result = HttpUtil.get(url);
        //结果集转对象
        WeixinGzhUser weixinGzhUser = JSONObject.parseObject(result, WeixinGzhUser.class);
        wxUserInfoByOpenId.setCity(weixinGzhUser.getCity());
        wxUserInfoByOpenId.setCountry(weixinGzhUser.getCountry());
        wxUserInfoByOpenId.setGroupid(weixinGzhUser.getGroupid());
        wxUserInfoByOpenId.setHeadimgurl(weixinGzhUser.getHeadimgurl());
        wxUserInfoByOpenId.setLanguage(weixinGzhUser.getLanguage());
        wxUserInfoByOpenId.setNickname(weixinGzhUser.getNickname());
        wxUserInfoByOpenId.setProvince(weixinGzhUser.getProvince());
        wxUserInfoByOpenId.setRemark(weixinGzhUser.getRemark());
        wxUserInfoByOpenId.setSex(weixinGzhUser.getSex());
        wxUserInfoByOpenId.setTagidList(weixinGzhUser.getTagidList());
        if (phone != null) {
            wxUserInfoByOpenId.setPhone(phone);
        }
        wxUserInfoByOpenId.setPlatform(platform);
        this.updateByPrimaryKeySelective(wxUserInfoByOpenId);
        return weixinGzhUser;
    }

    /**
     * 通过openId查询用户信息
     *
     * @param openId
     * @return
     */
    public WeixinGzhUser getWxUserInfoByOpenId(String openId, Integer platform) {
        Example example = new Example(WeixinGzhUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openid", openId);
        if (platform != null) {
            criteria.andEqualTo("platform", platform);
        }
        List<WeixinGzhUser> weixinGzhUsers = this.selectByExample(example);
        if (weixinGzhUsers.size() <= 0) {
            return null;
        }
        return weixinGzhUsers.get(0);
    }

    /**
     * 查询我的邀请人数
     */
    public int selectInviteCount(String openId, Integer platform) {
        Example example = new Example(WeixinGzhUser.class);
        example.createCriteria()
                .andEqualTo("platform", platform)
                .andEqualTo("qrSceneStr", openId);
        return selectCountByExample(example);
    }

    /**
     * 查询我邀请的人
     *
     * @param openId
     * @param platform
     * @return
     */
    public PageInfo<WeixinGzhUser> selectInviteList(Integer pageNum,Integer pageSize,String openId, Integer platform) {
        Example example = new Example(WeixinGzhUser.class);
        example.createCriteria()
                .andEqualTo("qrSceneStr", openId)
                .andEqualTo("platform", platform);
        example.orderBy("subscribeTime").desc();
        PageInfo<WeixinGzhUser> weixinGzhUsers = this.selectPage(pageNum,pageSize,example);
        for (WeixinGzhUser weixinGzhUser : weixinGzhUsers.getList()) {
            weixinGzhUser.setCity(null);
            weixinGzhUser.setCountry(null);
            weixinGzhUser.setGroupid(null);
            weixinGzhUser.setLanguage(null);
            weixinGzhUser.setPhone(null);
            weixinGzhUser.setProvince(null);
            weixinGzhUser.setQrSceneStr(null);
            weixinGzhUser.setOpenid(null);
            weixinGzhUser.setUnionid(null);
            weixinGzhUser.setSubscribeTime(null);
        }
        return weixinGzhUsers;
    }

    /**
     * 邀请排行榜
     *
     * @param platform
     * @return
     */
    public List<WeixinGzhUser> selectInviteRankingList(Integer platform) {
        List<WeixinGzhUser> weixinGzhUserList = weixinGzhUserMapper.selectInviteRanKingList(platform, DateUtil.getNowTime());
        return weixinGzhUserList;
    }

    /**
     * 生成二维码并返回二维码链接
     *
     * @param sceneStr openId
     * @return
     */
    public String getTicket(String sceneStr, Integer platform) {
        JSONObject json = new JSONObject();
        json.put("action_name", Constant.QR_LIMIT_STR_SCENE);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("scene_str", sceneStr);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("scene", jsonObject1);
        json.put("action_info", jsonObject2);
        String accessToken = weixinUtil.getAccessToken(platform);
        String result = HttpUtil.post(Constant.QR_CODE_URL + accessToken, json.toJSONString());
        JSONObject jsonObject = JSON.parseObject(result);
        String ticket = jsonObject.getString("ticket");
        return Constant.QR_CODE + ticket;
    }


    /**
     * 合并背景图和二维码
     *
     * @param qrImageUrl 二维码URL
     * @return
     */
    public File inviteQRCodeImage(String qrImageUrl, String bjImageUrl) throws IOException {
        OutputStream os = null;
        try {
            URL qrUrl = new URL(qrImageUrl);
            URL BjUrl = new URL(bjImageUrl);
            Image qr = ImageIO.read(qrUrl);
            Image bj = ImageIO.read(BjUrl);
            //背景图宽
            int width = bj.getWidth(null);
            //背景图高
            int height = bj.getHeight(null);
            //创建面板
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //合并图片
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(bj, 0, 0, null);
            g.drawImage(qr, 340, 820, 285, 285, null);
            g.dispose();
            //生成文件
            File file = new File(UUID.randomUUID() + ".jpeg");
            //图片写入到文件
            os = new FileOutputStream(file);
            ImageIO.write(bufferedImage, "jpeg", os);
            bufferedImage.flush();
            //返回路径
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }
    public WeixinGzhUser selectByPhone(String phone,Integer platform){
        Example example = new Example(WeixinGzhUser.class);
        example.createCriteria().andEqualTo("phone",phone).andEqualTo("platform",platform);
        List<WeixinGzhUser> weixinGzhUserList = this.selectByExample(example);
        if(weixinGzhUserList!=null&&weixinGzhUserList.size()!=0){
            return weixinGzhUserList.get(0);
        }
        return null;
    }

    public Integer countUserByphone(String phone,Integer platform){
        Example example = new Example(WeixinGzhUser.class);
        example.createCriteria().andEqualTo("phone",phone).andEqualTo("platform",platform);
        List<WeixinGzhUser> weixinGzhUserList = this.selectByExample(example);
        return weixinGzhUserList.size();
    }
}
